package org.example.command;

import org.example.model.HTMLDocument;
import org.example.service.spellcheck.SpellChecker;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;

import java.util.List;

public class SpellCheckCommand implements Command {
    private final HTMLDocument htmlDocument;
    private final SpellChecker spellChecker;

    public SpellCheckCommand(HTMLDocument htmlDocument, SpellChecker spellChecker) {
        this.htmlDocument = htmlDocument;
        this.spellChecker = spellChecker;
    }

    public static SpellCheckCommand create(HTMLDocument htmlDocument, SpellChecker spellChecker) {
        return new SpellCheckCommand(htmlDocument, spellChecker);
    }

    @Override
    public boolean execute() {
        // 遍历 HTML 文档的所有文本节点
        for (Element element : htmlDocument.getDocument().getAllElements()) {
            for (Node node : element.childNodes()) {
                if (node instanceof TextNode) {
                    String text = ((TextNode) node).text();
                    try {
                        // 使用 SpellChecker 进行拼写检查
                        List<String> corrections = spellChecker.checkSpelling(text);
                        corrections.forEach(System.out::println);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return true;
    }
}
